package com.cfl.mongodb.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cfl.mongodb.model.User;

@Controller
@RequestMapping("/")
public class UserController {
	
	@Autowired
	private MongoTemplate mongoTemplate;
	
	@RequestMapping("home")
	public Object home() {
		return "home";  
	}
	
	@RequestMapping("findByName")
	@ResponseBody
	public Object findByName(String name) {
		String dbName = mongoTemplate.getDb().getName();   
        System.out.println("数据库名为："+dbName);  
        
        Criteria criteria = new Criteria();
        criteria.and("name").is(name);  
        Query query = new Query();
        query.addCriteria(criteria);
        User user = mongoTemplate.findOne(query, User.class); 
        if(user != null) {
        		System.out.println("user："+user.toString()); 
        }
		return user;
	}
	
	@RequestMapping("findByAll")
	@ResponseBody
	public Object findByAll() {
		return mongoTemplate.findAll(User.class);
	}
}
